<template>
  <a-spin :spinning="loading">
    <div class="modal-header">
      <div class="modal-title">{{ l('CreateNewTenant') }}</div>
    </div>
    <slot></slot>
    <div class="modal-body">
      <a-form
        :model="form"
        @submit="handleSubmit"
        :rules="rules"
        ref="formRef"
        layout="vertical"
        labelAlign="right"
      >
        <!-- 租户名称 -->
        <a-form-item :label="l('TenancyCodeName')" name="tenancyName">
          <a-input :placeholder="l('TenancyCodeName')" v-model:value="form.tenancyName" />
        </a-form-item>

        <!-- 租户显示名称 -->
        <a-form-item :label="l('TenancyName')" name="displayTenancyName">
          <a-input :placeholder="l('TenancyName')" v-model:value="form.displayTenancyName" />
        </a-form-item>

        <!-- 使用主机数据库 -->
        <a-checkbox @change="UseHostDatabaseChange" v-model:checked="UseHostDatabasechecked">{{
          l('UseHostDatabase')
        }}</a-checkbox>
        <a-form-item :label="l('DatabaseConnectionString')" v-if="!UseHostDatabasechecked">
          <a-input
            :placeholder="l('DatabaseConnectionString') + l('Optional')"
            v-model:value="form.databaseConnectionString"
            required
          />
        </a-form-item>

        <!-- 管理员邮箱 -->
        <a-form-item :label="l('AdminEmailAddress')" name="emailAddress">
          <a-input
            :placeholder="l('EmailAddress')"
            v-model:value="form.emailAddress"
            required
            maxlength="255"
            type="email"
          />
        </a-form-item>

        <!-- 密码 -->
        <a-checkbox @change="passwordChange" v-model:checked="passwordchecked">
          {{ l('UseDefaultPassword') }}
          <span v-if="passwordchecked">{{ l(': 123qwe') }}</span>
        </a-checkbox>
        <a-form-item
          :label="l('Password')"
          v-if="!passwordchecked"
          has-feedback
          name="NextPassword"
        >
          <a-input
            :placeholder="l('Password')"
            type="password"
            required
            maxlength="32"
            minlength="6"
            v-model:value="form.NextPassword"
            autocomplete="off"
          />
        </a-form-item>
        <a-form-item
          :label="l('ConfirmPassword')"
          v-if="!passwordchecked"
          has-feedback
          name="newNextPassword"
        >
          <a-input
            :placeholder="l('ConfirmPassword')"
            type="password"
            required
            v-model:value="form.newNextPassword"
          />
        </a-form-item>

        <!-- 版本 -->
        <a-form-item :label="l('Edition')" has-feedback>
          <edition-select
            :placeholder="l('PleaseSelect')"
            :selectedEdition="selectedEdition"
            @change="selectedEditionChange($event)"
          ></edition-select>
        </a-form-item>

        <!-- 是否试用 -->
        <a-checkbox
          @change="checkedChange('isInTrialPeriod', $event)"
          :disabled="IsInTrialPerioddisabled"
          v-model:checked="isInTrialPeriod"
        >
          {{ l('IsInTrialPeriod') }}
        </a-checkbox>
        <br />

        <!-- 下次登录需要修改密码 -->
        <a-checkbox
          @change="checkedChange('shouldChangePasswordOnNextLogin', $event)"
          v-model:checked="shouldChangePasswordOnNextLogin"
        >
          {{ l('ShouldChangePasswordOnNextLogin') }}
        </a-checkbox>
        <br />

        <!-- 发送激活邮件 -->
        <a-checkbox
          v-if="false"
          @change="checkedChange('sendActivationEmail', $event)"
          v-model:checked="sendActivationEmail"
        >
          {{ l('SendActivationEmail') }}
        </a-checkbox>

        <!-- 是否激活 -->
        <a-checkbox @change="checkedChange('isActive', $event)" v-model:checked="isActive">
          {{ l('IsActive') }}
        </a-checkbox>

        <a-form-item class="btn--container"> </a-form-item>
      </a-form>
    </div>
    <div class="modal-footer">
      <a-button type="button" @click="close()">{{ l('Cancel') }}</a-button>
      <a-button type="primary" html-type="submit" @click="handleSubmit($event)">
        {{ l('Save') }}
      </a-button>
    </div>
  </a-spin>
</template>

<script lang="ts">
  import { ModalComponentBase } from '/@/shared/component-base';
  import { EditionSelect } from '/@/app/admin-shared';
  import { defineComponent } from 'vue';
  import { TenantServiceProxy, CreateTenantInput } from '/@/shared/service-proxies';

  export default defineComponent({
    name: 'create-tenant-component',
    components: {
      EditionSelect,
    },
    mixins: [ModalComponentBase],
    data() {
      return {
        confirmDirty: false,
        autoCompleteResult: [],
        UseHostDatabasechecked: true,
        passwordchecked: true,
        // 版本
        selectedEdition: {
          value: 0,
        },
        // 是否在试用期
        isInTrialPeriod: false,
        IsInTrialPerioddisabled: false,
        // 下次登录需要修改密码
        shouldChangePasswordOnNextLogin: false,
        // 发送激活邮件
        sendActivationEmail: false,
        // 是否激活
        isActive: true,
        IsUnlimitedchecked: false,
        // IsUnlimited
        isShowIsUnlimited: false,
        // 版本号
        editionId: 0,
        form: {
          tenancyName: '',
          displayTenancyName: '',
          emailAddress: '',
          NextPassword: '',
          newNextPassword: '',
          databaseConnectionString: '',
          subscriptionEndUtc: '',
        },
        rules: {
          subscriptionEndUtc: [
            {
              required: true,
              message: this.l('PleaseEnterASubscriptionEndDate'),
            },
          ],
          tenancyName: [
            {
              required: true,
              message: this.l('TheTenantCodeCannotBeEmpty'),
              trigger: 'blur',
            },
            {
              min: 3,
              message: this.l('MinLength', 3),
              trigger: 'blur',
            },
            {
              pattern: '^[a-zA-Z][a-zA-Z0-9_-]{1,}$',
              message: this.l(
                'OnlyNumbersAndLettersCanBeEnteredAndTheFirstCharacterCannotBeANumber',
              ),
              trigger: 'blur',
            },
          ],
          displayTenancyName: [
            {
              required: true,
              message: this.l('TheTenantDisplayNameCannotBeEmpty'),
              trigger: 'blur',
            },
            {
              min: 3,
              message: this.l('MinLength', 3),
              trigger: 'blur',
            },
          ],
          NextPassword: [
            { required: true, message: this.l('ThePasswordCannotBeEmpty'), trigger: 'blur' },
            {
              min: 6,
              message: this.l('MinLength', 6),
              trigger: 'blur',
            },
          ],
          newNextPassword: [{ validator: this.validateEqual, trigger: 'blur' }],
          emailAddress: [
            {
              required: true,
              message: this.l('AdministratorMailboxesCannotBeEmpty'),
            },
            {
              pattern: '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$',
              message: this.l('NotEmail'),
              trigger: 'blur',
            },
          ],
        },
        tenantService: new TenantServiceProxy(),
        CreateTenantInput: CreateTenantInput,
      };
    },
    methods: {
      /**
       * UseHostDatabaseChange
       */
      UseHostDatabaseChange(e) {
        this.UseHostDatabasechecked = eval(`${e.target.checked}`.toLowerCase());
      },
      /**
       * password
       */

      /**
       * 验证密码
       */
      validateEqual() {
        if (this.form.newNextPassword === '') {
          return Promise.reject(this.l('PleaseInputThePasswordAgain'));
        } else if (this.form.newNextPassword !== this.form.NextPassword) {
          return Promise.reject(this.l('TwoInputsDonotMatch'));
        } else {
          return Promise.resolve();
        }
      },
      /**
       * 版本选择
       */
      selectedEditionChange(e) {
        if (e && e.value) {
          this.IsInTrialPerioddisabled = true;
          this.isShowIsUnlimited = true;
          this.editionId = parseInt(e.value);
          this.isInTrialPeriod = false;
        } else {
          this.IsInTrialPerioddisabled = false;
          this.isShowIsUnlimited = false;
          this.editionId = 0;
        }
      },
      /**
       * 是否试用
       * 下次登录需要修改密码
       * 发送激活邮
       * 是否激活
       */
      checkedChange(type, e) {
        this[`${type}`] = eval(`${e.target.checked}`.toLowerCase()) as never;
      },

      /**
       * 提交表单
       */
      handleSubmit(e) {
        e.preventDefault();
        (this.form.subscriptionEndUtc as any) =
          !this.editionId || this.IsUnlimitedchecked ? null : this.form.subscriptionEndUtc;
        (this.$refs.formRef as any).validate().then(() => {
          let otherobj = {
            shouldChangePasswordOnNextLogin: this.shouldChangePasswordOnNextLogin,
            sendActivationEmail: this.sendActivationEmail,
            isInTrialPeriod: this.isInTrialPeriod,
            isActive: this.isActive,
            editionId: this.editionId == 0 ? null : this.editionId,
            tenancyName: this.form.tenancyName,
            name: this.form.displayTenancyName,
            adminEmailAddress: this.form.emailAddress,
            adminPassword: this.passwordchecked ? '123qwe' : this.form.NextPassword,
            connectionString: this.form.databaseConnectionString,
            subscriptionEndUtc: this.form.subscriptionEndUtc,
          };
          this.loading = true;
          this.tenantService
            .create(Object.assign(otherobj))
            .finally(() => {
              this.loading = false;
            })
            .then(() => {
              this.notify.success(this.l('SavedSuccessfully'));
              this.success(true);
            });
        });
      },
    },
  });
</script>

<style lang="less" scoped>
  :deep(.btn--container .ant-form-item-children) {
    display: block;
    margin: 10px auto;
    text-align: center;
  }
</style>
